﻿using HCMS.CommonDtos;
using HCMS.Dictionary;
using HCMS.DomainServiceManage.Cache.Base;
using HCMS.Entities.Base;
using HCMS.IRepositories.Base;
using HCMS.IServices.Base;
using HCMS.Repositories.Base;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace HCMS.Services.Base
{
    /// <summary>
    /// 敏感词 应用服务
    /// </summary>
    public class SensitiveWordsAppService : CommonAppService<BaseDbContext, SensitiveWords>, ISensitiveWordsAppService
    {
        private readonly IRepository<SensitiveWords> baseSensitiveWordsRepository;
        private readonly ISensitiveWordsRepository sensitiveWordsRepository;
        private readonly SensitiveWordsCacheManager sensitiveWordsCacheManager;

        public SensitiveWordsAppService(
            IRepository<SensitiveWords> baseSensitiveWordsRepository,
            ISensitiveWordsRepository sensitiveWordsRepository,
            SensitiveWordsCacheManager sensitiveWordsCacheManager
            ) : base(baseSensitiveWordsRepository)
        {
            this.baseSensitiveWordsRepository = baseSensitiveWordsRepository;
            this.sensitiveWordsRepository = sensitiveWordsRepository;
            this.sensitiveWordsCacheManager = sensitiveWordsCacheManager;
        }

        /// <summary>
        /// 管理 列表
        /// </summary>
        /// <param name="searchArgs">搜索 参数</param>
        /// <param name="pager">分页 参数</param>
        /// <returns></returns>
        public async Task<ListPagerDto<object>> ManageList(SearchArgsDto searchArgs, PagerArgsDto pager)
        {
            var sensitiveWords = await sensitiveWordsRepository.ManageList(searchArgs, pager);

            var result = new ListPagerDto<object>();
            result.PagerInfo = sensitiveWords.PagerInfo;

            var sensitiveWordsClassItems = new DictCommon().SensitiveWordsClassItems();

            var data = new List<object>();
            foreach (var item in sensitiveWords.Data)
            {
                var className = string.Empty;
                if (item.ClassId > 0)
                {
                    var classInfo = sensitiveWordsClassItems.FirstOrDefault(t => int.Parse(t.Value) == item.ClassId);
                    if (classInfo != null)
                    {
                        className = classInfo.Text;
                    }
                }

                data.Add(new
                {
                    id = item.Id,
                    createTime = item.CreateTime,
                    createUser = item.CreateUser,
                    updateTime = item.UpdateTime,
                    updateUser = item.UpdateUser,
                    status = item.Status,
                    title = item.Title,
                    className = className
                });
            }

            result.Data = data;

            return result;
        }

        /// <summary>
        /// 判断敏感词是否重复
        /// </summary>
        /// <remarks>
        /// 不允许创建重复的敏感词
        /// </remarks>
        /// <param name="id">当前的敏感词 Id</param>
        /// <param name="title">敏感词</param>
        /// <returns>true：重复，false：不存在重复</returns>
        public async Task<bool> HasRepeat(int id, string title)
        {
            if (string.IsNullOrWhiteSpace(title)) { return false; }

            title = title.Trim();

            if (id == 0)
            {
                var result = await BaseFirstOrDefaultAsync(t => t.Title.Trim() == title) != null;
                return result;
            }
            else
            {
                var result = await BaseFirstOrDefaultAsync(t => t.Id != id && t.Title.Trim() == title) != null;
                return result;
            }
        }

        /// <summary>
        /// 替换敏感词
        /// </summary>
        /// <remarks>
        /// 敏感词 替换为 * 
        /// </remarks>
        /// <param name="content">原始内容</param>
        /// <param name="classIds">分类 Ids</param>
        /// <returns>替换后的内容</returns>
        public async Task<string> SensitiveReplace(string content, int[] classIds)
        {
            if (string.IsNullOrWhiteSpace(content)) { return ""; }

            var all = await AllList();
            all = all.Where(t => t.Status == 0)?.ToList();
            if (all != null && all.Any() && classIds != null && classIds.Any())
            {
                all = all.Where(t => classIds.Contains(t.ClassId))?.ToList();
            }
            all = all ?? new List<SensitiveWords>();

            // 暴力匹配，不推荐。后续需要改进。KMP 字符串匹配算法
            foreach (var item in all)
            {
                if (!content.Contains(item.Title))
                {
                    continue;
                }

                var str = "";
                for (var i = 0; i < item.Title.Length; i++)
                {
                    str += "*";
                }

                content = content.Replace(item.Title, str);
            }

            return content;
        }

        /// <summary>
        /// 敏感词 提示
        /// </summary>
        /// <param name="content">原始内容</param>
        /// <param name="classIds">分类 Ids</param>
        /// <returns>存在敏感词，返回提示。不存在，返回空</returns>
        public async Task<string> SensitiveTips(string content, int[] classIds)
        {
            if (string.IsNullOrWhiteSpace(content)) { return ""; }

            var all = await AllList();
            all = all.Where(t => t.Status == 0)?.ToList();
            if (all != null && all.Any() && classIds != null && classIds.Any())
            {
                all = all.Where(t => classIds.Contains(t.ClassId))?.ToList();
            }
            all = all ?? new List<SensitiveWords>();

            // 暴力匹配，不推荐。后续需要改进。KMP 字符串匹配算法
            var result = new List<string>();
            foreach (var item in all)
            {
                if (content.Contains(item.Title))
                {
                    result.Add(item.Title);
                }
            }

            return string.Join("、", result);
        }

        /// <summary>
        /// 获取全部列表
        /// </summary>
        /// <param name="isRefreshCache">是否刷新缓存</param>
        /// <returns></returns>
        public async Task<List<SensitiveWords>> AllList(bool isRefreshCache = false)
        {
            if (!isRefreshCache)
            {
                var cacheValue = await sensitiveWordsCacheManager.GetList();
                if (cacheValue != null && cacheValue.Any())
                {
                    return cacheValue;
                }
            }

            var result = await sensitiveWordsRepository.AllList();
            if (result != null && result.Any())
            {
                await sensitiveWordsCacheManager.SetList(result);
            }

            return result ?? new List<SensitiveWords>();
        }

    }
}
